//
//  SearchViewController.m
//  meiyaya
//
//  Created by 张领瑞 on 2017/9/7.
//  Copyright © 2017年 ShiFeiEr. All rights reserved.
//

#import "SearchViewController.h"
#import "PrefixHeader.pch"

@interface SearchViewController ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate>

@property (nonatomic,strong)UISearchController *searchController;

@property (nonatomic,strong)UICollectionView *collectionView;//展示搜索历史与热门搜索
@property (nonatomic,strong)UITableViewController *searchTVC;//搜索结果显示
@property (nonatomic,strong)UISearchBar *searchBar;//搜索栏


@property(nonatomic,strong)NSMutableArray *historySearchDataArray;//搜索历史array
@property (nonatomic,strong)NSMutableArray *hotSearchDataArray;//热门搜索array
@property (nonatomic,strong)NSMutableArray *searchResultDataArray;//搜索结果array
@property  (nonatomic,copy)NSString *inputText;//搜索框搜索的文字
@property (nonatomic,strong)UIBarButtonItem *backItem;//重写返回按钮
@end

@implementation SearchViewController

#pragma mark 懒加载
// 懒加载创建searchBar
-(UISearchBar *)searchBar{
    if (_searchBar == nil) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 300, 35)];
        _searchBar.placeholder = @"找你变美的方法";
        _searchBar.delegate = self;
    }
    return _searchBar;
}

-(UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 20, SCREENWIDTH-20, SCREENHEIGHT-20-60) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

-(NSMutableArray *)historySearchDataArray{
    if (_historySearchDataArray == nil) {
        _historySearchDataArray = [[NSMutableArray alloc] init];
    }
    return _historySearchDataArray;
}

-(NSMutableArray *)hotSearchDataArray{
    if (_hotSearchDataArray == nil) {
        _hotSearchDataArray = [[NSMutableArray alloc] init];
    }
    return _hotSearchDataArray;
}

-(NSMutableArray *)searchResultDataArray{
    if (_searchResultDataArray == nil) {
        _searchResultDataArray = [[NSMutableArray alloc] init];
    }
    return _searchResultDataArray;
}

-(UIBarButtonItem *)backItem{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backToUpVC)];
    }
    return _backItem;
}
-(void)viewWillAppear:(BOOL)animated{
   
  self.view.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //添加searchBar
    self.navigationItem.titleView = self.searchBar;
    
    //添加colletionview
    [self.view addSubview:self.collectionView];
    
    //隐藏系统自带返回按钮
    [self.navigationItem  setHidesBackButton:YES];
    //重写返回按钮
    self.navigationItem.rightBarButtonItem = self.backItem;
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
   
    
    //注册头视图
    [self.collectionView registerNib:[UINib nibWithNibName:@"SearchSectionReusableView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionReusableView"];
    //注册脚视图
    [self.collectionView registerNib:[UINib nibWithNibName:@"FooterReusableView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterReusableView"];
    
    
    //注册单元格
    [self.collectionView registerNib:[UINib nibWithNibName:@"SearchViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"SearchViewCell"];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"EmptyCollectionViewCell" bundle:[NSBundle mainBundle]]  forCellWithReuseIdentifier:@"EmptyCollectionViewCell"];
   
    [self.searchTVC.tableView registerNib:[UINib nibWithNibName:@"SearchResultCell" bundle:[NSBundle mainBundle]]  forCellReuseIdentifier:@"SearchResultCell"];
    
    
   [self.hotSearchDataArray addObjectsFromArray:@[@"焚膏继晷",@"福建省",@"国防军工"]];
   [self.historySearchDataArray addObjectsFromArray:@[@"焚膏继晷",@"福建省",@"军工",@"军工",@"焚放假多久晷",@"焚膏发广告继晷"]];
    
    // Do any additional setup after loading the view.
}
#pragma mark 返回按钮响应
-(void)backToUpVC{
   
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UICollectionViewDataSource Method
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        if (self.historySearchDataArray.count!= 0) {
            return self.historySearchDataArray.count;
        }
        return 1;
    }else {
        if (self.hotSearchDataArray.count!= 0) {
            return self.hotSearchDataArray.count;
        }
        return 1;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell;
    if (indexPath.section == 0) {
        if (self.historySearchDataArray.count != 0){
            SearchViewCell *sCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchViewCell" forIndexPath:indexPath];
            sCell.backgroundImagView.image = [UIImage imageNamed:@"bg_3"];
            sCell.titlelLabel.text = self.historySearchDataArray[indexPath.item];
            cell = sCell;
        }else{//无历史搜索记录
            EmptyCollectionViewCell *eCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EmptyCollectionViewCell" forIndexPath:indexPath];
            
            eCell.emptyLabel.text = @"您还没有搜索记录哦～";
            cell = eCell;
        }
    }else if (indexPath.section == 1) {
        
        if (self.hotSearchDataArray.count != 0) {
            SearchViewCell *sCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchViewCell" forIndexPath:indexPath];
            sCell.backgroundImagView.image = [UIImage imageNamed:@"btg_1"];
            sCell.titlelLabel.text = self.hotSearchDataArray[indexPath.item];
            cell = sCell;
        }else{
           EmptyCollectionViewCell *eCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EmptyCollectionViewCell" forIndexPath:indexPath];;
            eCell.emptyLabel.text = @"还没有热门搜索～";
            cell = eCell;
        }
    }
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SearchSectionReusableView *searchSectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionReusableView" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            searchSectionView.sectionTitle.text = @"搜索历史";
        }
        if (indexPath.section == 1) {
            searchSectionView.sectionTitle.text = @"热门搜索";
        }
        view = searchSectionView;
    }
   
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        FooterReusableView *footerReview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterReusableView" forIndexPath:indexPath];
        footerReview.backgroundColor = [UIColor whiteColor];
        view = footerReview;
    }
    return view;
}

#pragma mark UICollectionViewLayoutDelegate Method
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 0, 10, 0);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *searchStr;
    float width;
    if (indexPath.section == 0) {
        if (self.historySearchDataArray.count == 0) {
            return CGSizeMake(SCREENWIDTH, 152);
        }
        searchStr = self.historySearchDataArray[indexPath.item];
    }
    if (indexPath.section == 1) {
        if (self.hotSearchDataArray.count == 0) {
            return CGSizeMake(SCREENWIDTH, 152);
        }
        searchStr = self.hotSearchDataArray[indexPath.item];
    }
    //计算文本长度
    width = [searchStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 14) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.width;
     return CGSizeMake(width+25, 24);
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREENWIDTH, 26);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(SCREENWIDTH, 10);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}




#pragma mark UISearchBarDelegate Method 
//开始输入
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
   if (searchBar == self.searchBar) {
        
    // 创建出搜索使用的表示图控制器
    self.searchTVC = [[UITableViewController  alloc] initWithStyle:UITableViewStylePlain];
    _searchTVC.tableView.dataSource = self;
    _searchTVC.tableView.delegate = self;
    // 使用表示图控制器创建出搜索控制器
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:_searchTVC];
    
    //搜索框检测代理
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.searchBar.delegate =self;
    //设置属性
    _searchController.searchBar.placeholder = SEARCHBAR_TIP;
    _searchController.view.backgroundColor = [UIColor whiteColor];
    _searchController.searchBar.barTintColor = MAINCOLOR;
    _searchController.searchBar.tintColor = [UIColor whiteColor];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;//不加的话，UISearchBar返回后会上移
    self.definesPresentationContext = YES;
       
    _searchController.hidesNavigationBarDuringPresentation = NO;
    self.navigationItem.titleView = _searchController.searchBar;
    [self presentViewController:_searchController animated:YES completion:^{
        // 当模态推出这个searchController的时候,需要把之前的searchBar隐藏,如果希望搜索的时候看不到热门搜索什么的,可以把这个页面给隐藏
      self.searchBar.hidden = YES;
      self.view.hidden = YES;
    }];
   }
    
    self.navigationItem.rightBarButtonItem = nil;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
   self.searchBar.hidden = NO;
   self.view.hidden = NO;
   [self.searchBar resignFirstResponder];
    self.navigationItem.rightBarButtonItem = self.backItem;
  
}
#pragma mark - UISearchResultsUpdating Method 
//监听搜索框中的值的变化
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    //获取输入的值
    self.inputText = searchController.searchBar.text;
    //搜索数据
    
}

#pragma mark UITableViewDataSource
// 设置搜索tableView cell个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //测试
    if (_searchResultDataArray.count == 0) {
        return 1;
    }
    return self.searchResultDataArray.count;
}
// 设置搜索tableView的cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  //测试
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    
    if (!cell) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    
    }
    cell.textLabel.text = @"111";
    return cell;
}
//设置cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


#pragma mark UITableViewDelegate
//设置搜索tableview 点击进入搜索结果
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转操作
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}
#pragma mark UISearchControllerDelegate Method
//当搜索页面消失的时候,让原先的搜索bar和View显示
-(void)didDismissSearchController:(UISearchController *)searchController{
   self.searchBar.hidden = NO;
   self.view.hidden = NO;
  [self.searchBar resignFirstResponder];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
